<?php
namespace app\common\model;

use think\facade\Db;
use think\helper\Hash;
/**
 * 后台用户模型
 */
class User extends Base 
{
	// 自动写入时间戳
    protected $autoWriteTimestamp = true;
    // 对密码进行加密
    public function setPasswordAttr($value)
    {
        return Hash::make((string)$value);
    }
    // 获取注册ip
    public function setLoginIpAttr()
    {
        return get_client_ip(0);
    }

    public function group(){
        return $this->belongsTo('Role','role','id');
    }
    /**
     * 用户登录
     * @param string $username 用户名
     * @param string $password 密码
     * @return bool|mixed
     */
    public function login($username = '', $password = '')
    {
    	$username = trim($username);
        $password = trim($password);

        // 用户名登录
        $map['username'] = $username;
        $map['status'] = 1;

        //查找用户
        $user = self::where($map)->find();
        if(!$user){
        	$this->error = '用户不存在或被禁用!';
        }else{
        	// 检查是否分配用户组
            if ($user['role'] == 0) {
                $this->error = '禁止访问，原因：未分配角色！';
                return false;
            }
            // 检查是可登录后台
            $role = Db::name('Role')->where(['id' => $user['role'],'status' => 1])->find();
            $access = $role['access'];
            if(!$access){
            	$this->error = '禁止访问，用户所在角色未启用或禁止访问后台！';
                return false;
            }
            if($user['role'] != 1){
            	$menu_auth = $role['menu_auth'];
            	$menu_auth = json_decode($menu_auth, true);
            	if(!$menu_auth){
            		$this->error = '未分配任何节点权限!';
            		return false;
            	}
            }

        	if (!Hash::check((string)$password, $user['password'])) {
                $this->error = '账号或者密码错误！';
            }else{
            	$uid = $user['id'];

            	// 更新登录信息
                $data['login_time'] = request()->time();
                $data['login_ip']   = get_client_ip(0);
                if(self::where('id',$uid)->update($data)){
                	$auth = [
                		'uid'        => $uid,
                		'role'       => $user['role'],
                		'role_name'  => $role['name'],
                		'username'   => $user['username'],
                		'nickname'   => $user['nickname'],
                		'login_time' => request()->time(),
                		'login_ip'   => get_client_ip(0)
                	];
                	session('user_auth', $auth);
        			session('user_auth_sign', data_auth_sign($auth));
                    return $uid;
                }else{
                	// 更新登录信息失败
                	$this->error = '登录信息更新失败，请重新登录！';
                    return false;
                }
            }
        }
        return false;        
    }
}